<template>
  <div class="search-container">
    <!-- 搜索模块 -->
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="rgb(50, 150, 250)"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>

    <!-- 搜索结果 -->
    <SearchResult v-if="isResultShow" :searchText="searchText"></SearchResult>
    <!-- 联想建议 -->
    <SearchSuggestion
      v-else-if="searchText"
      :searchText="searchText"
      @search="onSearch"
    ></SearchSuggestion>
    <!-- 历史记录 -->
    <SearchHistory v-else :searchHistories="searchHistories" @Search="onSearch"></SearchHistory>
  </div>
</template>

<script>
import SearchResult from '@/components/search/searchResult'
import SearchHistory from '@/components/search/searchHistory'
import SearchSuggestion from '@/components/search/searchSuggestion'
import { getItem, setItem } from '@/utils/storage.js'

export default {
  name: 'Search',
  data() {
    return {
      searchText: '', // 用户输入数据
      isResultShow: false, // 搜索结果的显示状态
      searchHistories: getItem('HISTORIES') || [] // 历史记录数据列表
    }
  },
  methods: {
    onSearch(val) {
      this.searchText = val // 将用户点击的字符串渲染到搜索框

      // 存储搜索记录
      const index = this.searchHistories.indexOf(val)
      if (index !== -1) {
        this.searchHistories.splice(index, 1) // 删除当前项
      }

      this.searchHistories.unshift(val) // 添加到历史列表开头
      this.isResultShow = true // 展示搜索结果
    },
    onCancel() {
      this.$router.back() // 历史记录后退
    }
  },
  watch: {
    // 监听历史记录是否变化，变化存储为本地
    searchHistories(val) {
      setItem('HISTORIES', val)
    }
  },
  components: {
    SearchResult,
    SearchHistory,
    SearchSuggestion
  }
}
</script>

<style lang="less" scoped>
.search-container {
  .van-search__action {
    color: #fff;
  }
}
</style>
